#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_timer(new QTimer(this))
    , m_inputDebounceTimer(new QTimer(this))
    , m_webSocket(new QWebSocket)
    , m_db(new DBManager)
    , m_gameSession(new GameSession)
    , m_server()
    , m_isClosing(false)
{
    ui->setupUi(this);

    QNetworkProxy::setApplicationProxy(QNetworkProxy::NoProxy);

    ui->statusbar->showMessage(tr("获取数据中..."), 0);

    m_timer->setInterval(1000);
    m_inputDebounceTimer->setSingleShot(true);
    m_inputDebounceTimer->setInterval(1000);

    connect(m_timer, &QTimer::timeout, [this]() {
        m_webSocket->close();
        QTimer::singleShot(100, [this]() {
            m_webSocket->open(QUrl(Config::instance().listenerUrl()));
        });
    });

    connect(m_gameSession, &GameSession::send_codes_fail, this, &MainWindow::do_send_codes_fail);
    connect(m_gameSession, &GameSession::player_join, this, &MainWindow::do_player_join);
    connect(m_gameSession, &GameSession::send_codes_success, [this](){
        ui->statusbar->showMessage(tr("弹幕数据发送成功"), 2000);
    });

    connect(ui->startGameBtn, &QPushButton::clicked, m_gameSession, &GameSession::start_game);
    connect(ui->startGameBtn, &QPushButton::clicked, this, &MainWindow::do_startGameBtn_clicked);
    connect(ui->rebootGameBtn, &QPushButton::clicked, m_gameSession, &GameSession::rebot_game);

    connect(m_gameSession, &GameSession::on_reboot_game, this, &MainWindow::do_rebootGameBtn_clicked);
    connect(m_gameSession, &GameSession::handle_cache, [this](const QString& str){
        QTimer::singleShot(2000, [this, str]() {
            ui->statusbar->showMessage(str, 2000);
        });
    });

    connect(m_gameSession, &GameSession::show_win, this, &MainWindow::do_show_win_byXinji);    // 显示弹窗
    connect(m_gameSession, &GameSession::show_gift, this, &MainWindow::do_show_gift_byXinji);  // 显示礼物
    connect(m_gameSession, &GameSession::add_item,
            [this]
            (const QString& player_id, const QString& player_name, const QString& player_HeadImgUrl, const QString& team, const QString& content, const int& progress, const QString& prefix)
            {
                m_server.additem(player_id, player_name, player_HeadImgUrl, team, content, progress, prefix);
            });

    connect(m_gameSession, &GameSession::del_item, [this] (const QString& player_id, const QString& player_name)
            {
                m_server.delitem(player_id, player_name);
            });

    connect(m_gameSession, &GameSession::clear_UI, this, &MainWindow::on_clearUI_clicked);
    connect(m_gameSession, &GameSession::clear_Popover, this, &MainWindow::on_clearPopover_clicked);
    connect(m_gameSession, &GameSession::chang_playerSort, this, &MainWindow::do_pushButton_clicked);
    connect(m_gameSession, &GameSession::on_quit_game, this, &MainWindow::close);

    connect(ui->pushButton, &QPushButton::clicked, this, &MainWindow::do_openLeaderboard_cs);
    connect(ui->pushButton_2, &QPushButton::clicked, [this]() {
        QMap<QString, QString> tmp = m_gameSession->get_users();
        QVector<QString> content;

        for (auto item = tmp.begin(); item != tmp.end(); item++) {
            content.push_back(item.key());
        }

        do_showLeaderboard_cs(0, content);
        do_showLeaderboard_cs(1, content);
    });
    connect(m_gameSession, &GameSession::openLeaderboard_cs, this, &MainWindow::do_openLeaderboard_cs);   // 打开 cs 排行榜
    connect(m_gameSession, &GameSession::showLeaderboard_cs, this, &MainWindow::do_showLeaderboard_cs);   // 显示 cs 排行榜

    connect(m_gameSession, &GameSession::show_killBroadcast, &m_server, &WebSocketServer::killBroadcast);        // 显示击杀播报
    connect(m_gameSession, &GameSession::clear_killBroadcast, &m_server, &WebSocketServer::clearKillBroadcast);  // 清空击杀播报

    connectionListening();
    initUi();
    on_joinRobotBtn_clicked();

    // 给主播使用时解放这两条代码
    hideWidgets();
    adjustWindowSize();
}


MainWindow::~MainWindow()
{
    delete ui;
    delete m_webSocket;
    delete m_db;
    delete m_gameSession;
}


void MainWindow::connectionListening()
{
    connect(m_webSocket, &QWebSocket::stateChanged, [this](QAbstractSocket::SocketState state) {
        switch (state) {
        case QAbstractSocket::ConnectedState:
            ui->danmu->clear();
            m_timer->stop();    // 连接成功关闭定时器
            ui->danmu->addItem(tr("》》》》》✅监听程序【连接成功】《《《《《"));
            break;
        case QAbstractSocket::UnconnectedState:
            ui->danmu->addItem(tr("》》》》》❌监听程序【未连接】《《《《《"));
            ui->danmu->addItem(tr("》》》》》😴空闲中《《《《《"));
            m_timer->start();   // 监听程序掉线后每隔 1 秒尝试连接一次看是否上线了
            break;
        case QAbstractSocket::ConnectingState:
            ui->danmu->addItem(tr("》》》》》🔎监听程序【连接中】《《《《《"));
            break;
        default:
            ui->danmu->addItem(tr("》》》》》🐞其他状态《《《《《"));
            break;
        }

        ui->danmu->scrollToBottom();
    });

    m_webSocket->open(QUrl(Config::instance().listenerUrl()));
    connect(m_webSocket, &QWebSocket::textMessageReceived, this, &MainWindow::on_message_receive);
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (m_isClosing) {
        event->accept();
        return;
    }

    QMessageBox::StandardButton reply = QMessageBox::question(
        this,
        tr("确认退出"),
        tr("您确定要退出程序吗？\n如果正在游戏中，退出会中止游戏。"),
        QMessageBox::Yes | QMessageBox::No
        );

    if (reply == QMessageBox::Yes) {
        m_isClosing = true;
        // 停止接收信息
        disconnect(m_webSocket, &QWebSocket::textMessageReceived, this, &MainWindow::on_message_receive);
        m_webSocket->close();
        event->ignore();
        m_gameSession->quit_game();
        QTimer::singleShot(1000, this, &QMainWindow::close);
    } else {
        event->ignore();
    }
}


void MainWindow::initUi()
{
    QSqlQuery query = m_db->selectData("game", "*", QString("id=%1").arg(Config::instance().gameId()));

    if (query.next()) {
        ui->selectGame_comboBox->addItem(query.value("gameName").toString());
    }

    set_Uuid();
    set_gift();
    ui->statusbar->showMessage(tr("获取数据成功"), 3000);
    ui->startGameBtn->setEnabled(false);
    ui->showOverallRankingBut->setEnabled(false);
    ui->showCurrentRankingBut->setEnabled(false);
    ui->rebootGameBtn->setEnabled(false);
    ui->password_Input->setPlaceholderText(tr("输入主播ID之后，才能点击“开始游戏”按钮"));
    ui->giftNum_input->setValidator(new QIntValidator(0, 99999, this));
    ui->progressValue->setValidator(new QIntValidator(-1, 100, this));
}


void MainWindow::set_gift(int gameId)
{
    ui->outGift_input->clear();

    auto giftDataList = m_db->get_gift(Config::instance().gameId());

    if (giftDataList.size() <= 1) {
        ui->outGift_input->addItem(tr("改游戏没有配置礼物"));
        return;
    }

    // 插入排序后的数据到UI和存储到xinji类
    for (const auto& giftData : giftDataList)
    {
        ui->outGift_input->addItem(QString("【%1】：%2").arg(giftData.id).arg(giftData.name));
        m_gameSession->setGifts(QString("%1").arg(giftData.id, 3, 10, QChar('0')), giftData.name);
    }
}


void MainWindow::set_Uuid()
{
    QUuid uuid = QUuid::createUuid();
    QString uuidString = uuid.toString(QUuid::WithoutBraces);
    ui->gameId_input->setText(uuidString);
    ui->gameId_input->setReadOnly(true);
    m_gameSession->set_Uuid(uuidString);
}


AnchorInfo MainWindow::findAnchorInfo(const QString &anchorId)
{
    AnchorInfo info;
    info.exists = false;

    try {
        QSqlQuery query = m_db->selectData("user", "*", QString("id = '%1'").arg(anchorId));

        if (query.isActive() && query.next()) {
            info.exists = true;
            info.id = query.value("id").toString();
            info.name = query.value("username").toString();
        }
    } catch (const std::exception& e) {
        qDebug() << "查询主播信息时发生异常:" << e.what();
    }

    return info;
}

void MainWindow::on_message_receive(const QString &message)
{
    QTime currentTime   = QTime::currentTime();
    QString date        = currentTime.toString("hh:mm:ss");
    QJsonDocument doc   = QJsonDocument::fromJson(message.toUtf8());

    if (doc.isNull())
    {
        QString errorMsg = QString("[%1] ⚠️ 消息格式错误: %2").arg(date).arg(message);
        ui->danmu->addItem(errorMsg);
        qDebug() << errorMsg;
        return;
    }

    QJsonObject obj = doc.object();
    QJsonValue data = obj["Data"];
    QJsonValue type = obj["Type"];

    QJsonValue user     = data["User"]; // 获取用户信息
    QString userName    = user["NickName"].toString();
    QString userAvatar  = user["Avatar"].toString();

    QString logMessage, giftTxt;

    TiktokGiftInfo  giftInfo;
    giftInfo.userName       = userName;
    giftInfo.userAvatar     = userAvatar;

    if (type.toInt() == 6)
    {
        giftInfo.giftName       = data["GiftName"].toString(); // 礼物名
        giftInfo.giftPrice      = data["GiftPrice"].toDouble();// 礼物价格
        giftInfo.giftCount      = data["GiftCount"].toInt();   // 单次赠送数量

        int code = m_db->get_code(giftInfo.giftName);
        giftTxt = m_gameSession->append_user(code, giftInfo);

        logMessage = QString(tr("🎁[%1] 用户: %2, 送出: %3, 数量: %4"))
                         .arg(date)
                         .arg(userName)
                         .arg(giftInfo.giftName)
                         .arg(giftInfo.giftCount);
    }
    else if (type.toInt() == 4)
    {
        giftInfo.giftName   = QString("Like");
        giftInfo.giftPrice  = 0;
        giftInfo.giftCount  = data["LikeCount"].toInt();

        int code = m_db->get_code(QString(giftInfo.giftName));
        if (code != 0) {
            giftTxt = m_gameSession->append_user(code, giftInfo);
        }

        logMessage = QString(tr("💖[%1] 用户: %2, 送出了点赞，数量: %3"))
                         .arg(date)
                         .arg(userName)
                         .arg(giftInfo.giftCount);
    }
    else if (type.toInt() == 3)
    {
        logMessage = QString("📢[%1] User: %2, : %3")
                         .arg(date)
                         .arg(userName)
                         .arg(data["Content"].toString());
    }

    if (logMessage != "") {
        ui->danmu->addItem(logMessage);
    }

    if (giftTxt != "") {
        ui->historyList->addItem(giftTxt);
        ui->danmu->addItem("✅ Record generated and appended");
    }

    ui->danmu->scrollToBottom();
    ui->historyList->scrollToBottom();
}





void MainWindow::do_send_codes_fail(const QString &errInfo)
{
    ui->statusbar->showMessage(QString("弹幕发送失败：%1").arg(errInfo), 5000);
}


void MainWindow::do_player_join(const QString &user_nickname, const QString &user_id)
{
    QString player = QString("【%1】：%2").arg(user_id).arg(user_nickname);
    ui->playerId_comboBox->addItem(player);
    ui->selectPlayer->addItem(player);
    ui->killerSelect->addItem(player);
    ui->victimSelect->addItem(player);
}

void MainWindow::on_clearPopover_clicked()
{
    this->m_server.onClearPopover();
}


void MainWindow::do_showTempNotification(const QString& title, const QString& message, NotificationType type, int duration = 3000)
{
    QSystemTrayIcon* notifier = new QSystemTrayIcon(this);

    QStyle::StandardPixmap iconType;
    QSystemTrayIcon::MessageIcon messageIcon;

    switch (type) {
    case NotificationType::Information:
        iconType = QStyle::SP_MessageBoxInformation;
        messageIcon = QSystemTrayIcon::Information;
        break;
    case NotificationType::Warning:
        iconType = QStyle::SP_MessageBoxWarning;
        messageIcon = QSystemTrayIcon::Warning;
        break;
    case NotificationType::Critical:
        iconType = QStyle::SP_MessageBoxCritical;
        messageIcon = QSystemTrayIcon::Critical;
        break;
    case NotificationType::Question:
        iconType = QStyle::SP_MessageBoxQuestion;
        messageIcon = QSystemTrayIcon::NoIcon;
        break;
    default:
        iconType = QStyle::SP_MessageBoxInformation;
        messageIcon = QSystemTrayIcon::Information;
    }

    notifier->setIcon(QApplication::style()->standardIcon(iconType));
    notifier->show();
    notifier->showMessage(title, message, messageIcon, duration);

    connect(notifier, &QSystemTrayIcon::messageClicked, notifier, &QSystemTrayIcon::deleteLater);
    QTimer::singleShot(duration, notifier, &QSystemTrayIcon::deleteLater);
}


void MainWindow::do_showRankingBut_clicked()
{
    m_server.showRanking();
}


void MainWindow::do_pushButton_clicked(const QString &userId, const QString &sortValue)
{
    m_server.changePlayerSort(
        userId,
        sortValue.toInt()
        );
}

// 隐藏ui
void MainWindow::hideWidgets()
{
    ui->danMuBtn->hide();
    ui->likeBtn->hide();
    ui->showCurrentRankingBut->hide();
    ui->showOverallRankingBut->hide();
    ui->letfWinBtn->hide();
    ui->rightWinBtn->hide();
    ui->leftGift_btn->hide();
    ui->rightGift_btn->hide();
    ui->clearUI->hide();

    hideAllWidgets(ui->formLayout_2);
    delete ui->formLayout_2;
    ui->formLayout_2 = nullptr;  // 置空指针，防止野指针
}


void MainWindow::hideAllWidgets(QLayout *layout) {
    if (!layout) return;

    // 遍历布局中的所有项
    for (int i = 0; i < layout->count(); ++i) {
        QLayoutItem* item = layout->itemAt(i);
        if (item) {
            // 如果是控件，则隐藏
            if (QWidget* widget = item->widget()) {
                widget->hide();
            }
            // 如果是嵌套布局，则递归处理
            else if (QLayout* childLayout = item->layout()) {
                hideAllWidgets(childLayout);
            }
        }
    }
}


void MainWindow::adjustWindowSize()
{
    int newWidth = 1300;
    int newHeight = 300;
    resize(newWidth, newHeight);
}


void MainWindow::do_rebootGameBtn_clicked()
{
    m_gameSession->quit_game();
    ui->danmu->clear();
    ui->historyList->clear();

    set_Uuid();

    m_gameSession->clear_users();
    ui->playerId_comboBox->clear();
    ui->giftNum_input->clear();

    ui->startGameBtn->setText(tr("开始游戏"));
    ui->statusbar->showMessage(tr("已重开游戏"), 3000);

    ui->startGameBtn->setEnabled(true);
    on_joinRobotBtn_clicked();
}


void MainWindow::do_startGameBtn_clicked()
{
    ui->startGameBtn->setEnabled(false);
    ui->startGameBtn->setText(tr("正在游戏中"));
    do_showTempNotification(tr("温馨提示"), tr("正在游戏中，请不要关闭弹幕软件，正在向服务器传输数据"), NotificationType::Information, 1000);
}

void MainWindow::on_likeBtn_clicked() {
    int index = ui->playerId_comboBox->currentIndex();

    QJsonObject userObject;
    userObject["Nickname"]  = m_gameSession->find_users(index + 1);

    QJsonObject dataObject;
    dataObject["User"]      = userObject;
    dataObject["LikeCount"] = 1;

    QJsonObject likeMessageObject;
    likeMessageObject["Type"] = 4;
    likeMessageObject["Data"] = dataObject;

    QJsonDocument jsonDoc(likeMessageObject);
    QString likeMessageJson = jsonDoc.toJson(QJsonDocument::Compact);

    on_message_receive(likeMessageJson);
}

void MainWindow::on_danMuBtn_clicked()
{
    int index = ui->playerId_comboBox->currentIndex();
    QJsonObject userObject;
    userObject["Nickname"]  = m_gameSession->find_users(index + 1);

    QJsonObject dataObject;
    dataObject["User"]      = userObject;
    dataObject["Content"]   = "Entering game";

    QJsonObject likeMessageObject;
    likeMessageObject["Type"] = 1;
    likeMessageObject["Data"] = dataObject;

    QJsonDocument jsonDoc(likeMessageObject);
    QString likeMessageJson = jsonDoc.toJson(QJsonDocument::Compact);

    on_message_receive(likeMessageJson);
}

void MainWindow::on_giftButton_clicked()
{
    int index = ui->playerId_comboBox->currentIndex();
    int gift_index = ui->outGift_input->currentIndex();

    if (index < 0 || gift_index < 0) {
        ui->statusbar->showMessage(tr("请选择有效的玩家和礼物"), 3000);
        return;
    }

    QJsonObject userObject;
    userObject["NickName"] = m_gameSession->find_users(index + 1);

    QJsonObject dataObject;
    dataObject["User"] = userObject;
    dataObject["GiftName"] = m_db->get_gift_by_index(gift_index);

    dataObject["method"] = "送出";

    bool ok;
    int giftCount = ui->giftNum_input->text().toInt(&ok);
    if (!ok || giftCount <= 0) {
        giftCount = 1; // 设置默认值
    }

    dataObject["GiftCount"] = giftCount;
    int repeatCount = 1;
    dataObject["RepeatCount"] = repeatCount;

    QJsonObject likeMessageObject;
    likeMessageObject["Type"] = 6;
    likeMessageObject["Data"] = dataObject;

    QJsonDocument jsonDoc(likeMessageObject);
    QString likeMessageJson = jsonDoc.toJson(QJsonDocument::Compact);

    on_message_receive(likeMessageJson);
}


void MainWindow::on_selectGame_comboBox_activated(int index)
{
    this->set_gift(index);
}


void MainWindow::on_showOverallRankingBut_clicked()
{
    QJsonObject message;
    message["type"]     = "show";
    message["anchorId"] = ui->password_Input->text();
    message["Uuid"]     = ui->gameId_input->text();
    message["gameId"]   = Config::instance().gameId();
    message["scope"]    = "month";

    if (QWebSocket* client = m_server.findClientByName("popover")) {
        m_server.sendJsonToClient(client, message);
        qDebug() << "显示总局排行榜";
    }
}


void MainWindow::on_showCurrentRankingBut_clicked()
{
    QJsonObject message;
    message["type"]     = "show";
    message["anchorId"] = ui->password_Input->text();
    message["Uuid"]     = ui->gameId_input->text();
    message["scope"]    = "game";

    if (QWebSocket* client = m_server.findClientByName("popover")) {
        m_server.sendJsonToClient(client, message);
        qDebug() << "显示当局排行榜";
    }
}


void MainWindow::do_openLeaderboard_cs()
{
    QUrl url(LEADERBOARD_CS_URL);

    if (url.isValid()) {
        bool success = QDesktopServices::openUrl(url);
        if (success) {
            qDebug() << "成功打开浏览器并访问 cs 排行榜" ;
        } else {
            qDebug() << "无法打开浏览器访问 cs 排行榜" ;
        }
    } else {
        qDebug() << "无效的 URL:" ;
    }
}


void MainWindow::do_showLeaderboard_cs(const int &team, const QVector<QString> &playerNames)
{
    QJsonArray arr;
    QJsonObject obj;

    obj["Uuid"]     = ui->gameId_input->text();
    obj["anchorId"] = ui->password_Input->text();
    obj["team"]     = team;

    for (auto item = playerNames.begin(); item != playerNames.end(); item++) {
        arr.push_back(*item);
    }

    obj["playerNames"] = arr;
    m_server.showLeaderboard_cs(obj);
}


void MainWindow::on_joinRobotBtn_clicked()
{
    int size = m_gameSession->get_users_count();
    m_gameSession->join_users(QString(tr("【测试用】机器人-%1")).arg(size + 1), QString("%1").arg(size + 1, 4, 10, QChar('0')));
    ui->statusbar->showMessage(QString(tr("已加入默认机器人用户%1----%2")).arg(QString(tr("机器人-%1")).arg(size + 1)).arg(QString("%1").arg(size + 1, 4, 10, QChar('0'))), 2000);
}


void MainWindow::on_openWinAppBtn_clicked()
{
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setText(Config::instance().popoverUrl());
    ui->statusbar->showMessage(QString(tr("弹窗地址：%1，已复制到剪贴板")).arg(clipboard->text()), 2000);
}


// 添加玩家
void MainWindow::on_addPlayer_clicked()
{
    int playerIndex     = ui->selectPlayer->currentIndex() + 1;
    QString playerId    = QString("%1").arg(playerIndex, 4, 10, QChar('0'));
    QString playerName  = m_gameSession->find_users(playerIndex);
    QString playerAvatar= m_gameSession->get_user_avatar(playerId);
    QString content     = ui->Playerlifebar->text() == "" ? "0" : ui->Playerlifebar->text();
    int progress        = ui->progressValue->text().toInt();
    QString prefix      = ui->namePrefix->text();
    QString team        = "blue";

    if (ui->selectPlayerTeam->currentText() == "红色方") {
        team = "red";
    }

    m_server.additem(playerId, playerName, playerAvatar, team, content, progress, prefix);
}


// 删除玩家
void MainWindow::on_delPlayer_clicked()
{
    int playerIndex     = ui->selectPlayer->currentIndex() + 1;
    QString playerId    = QString("%1").arg(playerIndex, 4, 10, QChar('0'));
    QString playerName  = m_gameSession->find_users(playerIndex);
    m_server.delitem(playerId, playerName);
}


void MainWindow::on_clearUI_clicked()
{
    m_server.onClearUI();
}


void MainWindow::on_letfWinBtn_clicked()
{
    bool has_avatar = false;
    int index       = 1;
    QString id      = ui->password_Input->text();
    QString name    = "左方玩家";
    QString content = "胜利了！";

    m_server.leftWin(has_avatar, index, name, "", content, id);
}


void MainWindow::on_rightWinBtn_clicked()
{
    bool has_avatar = false;
    int index       = 0;
    QString id      = ui->password_Input->text();
    QString name    = "右方玩家";
    QString content = "胜利了！";

    m_server.rightWin(has_avatar, index, name, "", content, id);
}


void MainWindow::on_leftGift_btn_clicked()
{
    bool has_avatar = true;
    int index       = 1;
    QString id      = ui->password_Input->text();
    QString name    = "左方玩家";
    QString content = "嘉年华 * 12";

    m_server.leftGiftWin(has_avatar, index, name, "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png", content, id);
}


void MainWindow::on_rightGift_btn_clicked()
{
    bool has_avatar = true;
    int index       = 0;
    QString id      = ui->password_Input->text();
    QString name    = "右方玩家";
    QString content = "嘉年华 * 66";

    m_server.rightGiftWin(has_avatar, index, name, "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png", content, id);
}


void MainWindow::do_show_win_byXinji(const QString &player_name, const QString &player_HeadImgUrl, const QString &team, const QString &content)
{
    if (team == "left") {
        bool has_avatar = true;
        int index = 0;
        QString id = ui->password_Input->text();

        m_server.leftWin(has_avatar, index, player_name, player_HeadImgUrl, content, id);
    }
    else if (team == "right") {
        bool has_avatar = true;
        int index = 1;
        QString id = ui->password_Input->text();

        m_server.rightWin(has_avatar, index, player_name, player_HeadImgUrl, content, id);
    }
    else {
        qDebug() << "没有传入团队名-显示弹窗";
    }
}


void MainWindow::do_show_gift_byXinji(const QString &player_name, const QString &player_HeadImgUrl, const QString &team, const QString &content)
{
    if (team == "left") {
        bool has_avatar = true;
        int index = 0;
        QString id = ui->password_Input->text();

        m_server.leftGiftWin(has_avatar, index, player_name, player_HeadImgUrl, content, id);
    }
    else if (team == "right") {
        bool has_avatar = true;
        int index = 1;
        QString id = ui->password_Input->text();

        m_server.rightGiftWin(has_avatar, index, player_name, player_HeadImgUrl, content, id);
    }
    else {
        qDebug() << "没有传入团队名-显示礼物";
    }
}


void MainWindow::on_password_Input_textChanged(const QString &arg1)
{
    bool isValid = true;
    QString errorMsg;

    if (arg1.isEmpty()) {
        isValid = false;
        errorMsg = "ID不能为空";
    } else if (arg1.length() < 4) {
        isValid = false;
        errorMsg = "ID长度不能少于4个字符";
    } else if (!arg1.at(0).isLetter() && !arg1.at(0).isDigit()) {
        isValid = false;
        errorMsg = "ID必须以字母或数字开头";
    }

    // 无论输入是否有效，都要先断开之前的连接
    disconnect(m_inputDebounceTimer, &QTimer::timeout, nullptr, nullptr);

    if (isValid)
    {
        // 如果定时器已经在运行，先停止
        if (m_inputDebounceTimer->isActive()) {
            m_inputDebounceTimer->stop();
        }

        // 启动定时器
        m_inputDebounceTimer->start();

        // 建立新的连接
        connect(m_inputDebounceTimer, &QTimer::timeout, [this, arg1]() {
            ui->statusbar->showMessage(tr("正在搜索主播..."), 0);

            AnchorInfo anchorInfo = findAnchorInfo(arg1);

            if (anchorInfo.exists)
            {
                ui->password_Input->setEnabled(false);
                ui->startGameBtn->setEnabled(true);
                ui->showOverallRankingBut->setEnabled(true);
                ui->showCurrentRankingBut->setEnabled(true);
                ui->rebootGameBtn->setEnabled(true);

                ui->password_Input->setText(anchorInfo.id);
                m_gameSession->setAnchorId(anchorInfo.id);

                ui->password_Input->setStyleSheet("QLineEdit { background-color: #e6ffe6; border: 1px solid green; }");

                ui->statusbar->showMessage(tr("用户已找到，可以开始游戏"), 3000);
                setWindowTitle(QString(tr("当前主播：%1")).arg(anchorInfo.name));

                do_showTempNotification(tr("正确"), QString(tr("已查询到主播：%1，您可以点击开始游戏了")).arg(anchorInfo.name), NotificationType::Information, 3000);
            }
            else {
                ui->statusbar->showMessage(tr("用户不存在"), 3000);
                ui->password_Input->setStyleSheet("QLineEdit { background-color: #ffe6e6; border: 1px solid red; }");
                do_showTempNotification(tr("错误"), tr("错误通过改ID没有查询到主播"), NotificationType::Critical, 1000);
            }
        });
    }
    else if (!arg1.isEmpty()) {
        ui->statusbar->showMessage(errorMsg, 3000);
        ui->password_Input->setStyleSheet("QLineEdit { background-color: #ffffd9; border: 1px solid yellow; }");
    }
    else {
        ui->password_Input->setStyleSheet("");
        ui->statusbar->showMessage(tr("请输入主播ID"), 3000);
    }
}


// 点击显示击杀播报
void MainWindow::on_killBroadcast_clicked()
{
    QString killerId = QString("%1").arg(ui->killerSelect->currentIndex() + 1, 4, 10, QChar('0'));
    QString victimId = QString("%1").arg(ui->victimSelect->currentIndex() + 1, 4, 10, QChar('0'));
    int killBroadcastId = ui->broadcastSelect->currentIndex();
    m_gameSession->killBroadcast(killerId, victimId, killBroadcastId);
}


// 清空击杀播报队列
void MainWindow::on_clearBroadcast_clicked()
{
    m_gameSession->clearKillBroadcast();
}


void MainWindow::on_testWebBtn_clicked()
{
    on_letfWinBtn_clicked();
    on_rightWinBtn_clicked();
    on_leftGift_btn_clicked();
    on_rightGift_btn_clicked();
}


void MainWindow::on_copyGameUiBtn_clicked()
{
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setText(Config::instance().gameUiUrl());
    ui->statusbar->showMessage(QString(tr("游戏UI地址：%1，已复制到剪贴板")).arg(clipboard->text()), 2000);
}
